﻿using System;
using System.Linq;
using System.Reflection;

namespace HotelManageSystem.Domain.Entities
{
    public static class CopyToExtensions
    {
        public static void CopyTo(this object source, object destination)
        {
            if (source != null)
            {
                Type t = source.GetType();
                var obj = destination;
                Type t2 = obj.GetType();
                PropertyInfo[] destPropertiesArray = t2.GetProperties();
                PropertyInfo[] objPropertiesArray = t.GetProperties();
                foreach (var propertyInfo in objPropertiesArray)
                {
                    bool ok = true;
                    PropertyInfo info = propertyInfo;
                    PropertyInfo match =
                        destPropertiesArray.FirstOrDefault(x => x.Name == info.Name);

                    if (match == null)
                    {
                        ok = false;
                    }
                    else
                    {
                        if (match.PropertyType != propertyInfo.PropertyType)
                        {
                            ok = false;
                        }
                    }

                    if (ok)
                    {
                        var val = propertyInfo.GetValue(source, null);
                        match.SetValue(obj, val, BindingFlags.Default, null, null, null);
                    }
                }
            }
            // return obj;
        }
    }
}
